<template>
  <el-form ref="refDialogForm" class="set-dialog-form" :label-width="language === 'en' ? '180px' : '80px'"
    :model="formData" :rules="rules">
    <el-row>
      <el-col :span="12">
        <el-form-item :label="$t('travelAgency.tripDay')" prop="dayIndex">
          <TextInput v-model="formData.dayIndex" :label="$t('travelAgency.tripDay')" :maxlength="4" type="number" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('fleet.departure')" prop="startRegionCode">
          <CascaderArea v-model="formData.startRegionCode" style="width: 100%" :label="$t('fleet.departure')" :level="2"
            @change="handleRegionChange('1', $event)" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('fleet.destination')" prop="endRegionCode">
          <CascaderArea v-model="formData.endRegionCode" style="width: 100%" :label="$t('fleet.destination')" :level="2"
            @change="handleRegionChange('2', $event)" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('public.departure')" prop="startAddress">
          <span style="display: flex; align-items: center; flex: 1">
            <TextInput v-model="formData.startAddress" :placeholder="
                g_rules.zhAndEnShowMsg(
                  $t('public.pleaseSelect'),
                  $t('public.departure')
                )
              " @input="handleAddressChange('1')" />
            <el-button text @click="handleMapSelect('1')">{{
              $t('public.map')
              }}</el-button>
          </span>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('public.destination')" prop="endAddress">
          <span style="display: flex; align-items: center; flex: 1">
            <TextInput v-model="formData.endAddress" :placeholder="
                g_rules.zhAndEnShowMsg(
                  $t('public.pleaseSelect'),
                  $t('public.destination')
                )
              " @input="handleAddressChange('2')" />
            <!-- readonly
            @click="handleMapSelect('2')" -->
            <el-button text @click="handleMapSelect('2')">{{
              $t('public.map')
              }}</el-button>
          </span>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <SearchMap v-if="searchMapVisible" v-model="searchMapVisible" :type="searchMapType" :regionName="regionName"
    @add="handleAddRegion" />
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  row: {
    type: Object,
    default: () => { }
  }
})

const { language } = storeToRefs(useAppStore())
const refDialogForm = ref(null)
const formData = ref({
  startRegionCode: '',
  startAddress: '',
  startLocation: {
    lng: '',
    lat: ''
  },
  endRegionCode: '',
  endAddress: '',
  endLocation: {
    lng: '',
    lat: ''
  },
  dayIndex: ""
})
const rules = {
  dayIndex: g_rules.commonInputText(g_t('travelAgency.tripDay')),
  startRegionCode: g_rules.selectRule(g_t('fleet.departure')),
  startAddress: g_rules.selectRule(g_t('public.departure')),
  endRegionCode: g_rules.selectRule(g_t('fleet.destination')),
  endAddress: g_rules.selectRule(g_t('public.destination')),
}
const searchMapVisible = ref(false)
const searchMapType = ref('')
const regionName = ref('')

onMounted(async () => {
  if (props.type === 'edit') {
    const { row } = props
    g_utils.assignFormData(formData.value, row)
    formData.value.startLocation = await g_utils.getAMapLocation(
      g_utils.getRegionName(row.startRegionCode) + row.startAddress
    )
    formData.value.endLocation = await g_utils.getAMapLocation(
      g_utils.getRegionName(row.endRegionCode) + row.endAddress
    )
    console.log('childForm.value', formData.value)
  } else {
    formData.value.startRegionCode = await g_utils.getCurCityCode()
  }
})

const handleRegionChange = (type, data) => {
  const prefix = type == '1' ? 'start' : 'end'
  formData.value[`${prefix}RegionCode`] = data.lastCode
  formData.value[`${prefix}Address`] = ''
  formData.value[`${prefix}Location`] = {
    lng: '',
    lat: ''
  }
  getLocation(type)
}

const handleAddressChange = type => {
  // console.log('handleAddressChange', type, formData.value.startAddress)
  getLocation(type)
}

// 根据全路径名称获取经纬度
const getLocation = g_.debounce(async type => {
  const prefix = type == '1' ? 'start' : 'end'
  const regionCode = formData.value[`${prefix}RegionCode`]
  const address = formData.value[`${prefix}Address`]
  if (regionCode && address) {
    formData.value[`${prefix}Location`] = await g_utils.getAMapLocation(
      g_utils.getRegionName(regionCode) + address
    )
  } else {
    formData.value[`${prefix}Location`] = {
      lng: '',
      lat: ''
    }
  }
  console.log(`${prefix}Location`, formData.value[`${prefix}Location`])
}, 300)

const handleMapSelect = type => {
  searchMapVisible.value = true
  searchMapType.value = type
  // 获取对应类型的区域编码和地址
  const { startRegionCode, startAddress, endRegionCode, endAddress } =
    formData.value
  const [regionCode, address] =
    type === '1' ? [startRegionCode, startAddress] : [endRegionCode, endAddress]
  regionName.value = g_utils.getRegionName(regionCode, '') + address
}

const handleAddRegion = (type, data) => {
  // console.log('handleAddRegion', type, data)
  const { regionCode, address, lnglat } = data
  const prefix = type === '1' ? 'start' : 'end'

  formData.value[`${prefix}RegionCode`] = regionCode[regionCode.length - 1]
  formData.value[`${prefix}Address`] = address
  formData.value[`${prefix}Location`] = {
    lng: lnglat[0],
    lat: lnglat[1]
  }
  refDialogForm.value.validateField(`${prefix}RegionCode`)
}

defineExpose({
  refDialogForm,
  formData
})
</script>

<style scoped lang="scss"></style>